package com.dgut.leave.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dgut.common.util.ExtAjaxResponse;
import com.dgut.common.util.ExtPageable;
import com.dgut.common.util.SessionUtil;
import com.dgut.common.util.WorkflowVariable;
import com.dgut.leave.entity.Leave;
import com.dgut.leave.entity.LeaveQueryDTO;
import com.dgut.leave.service.ILeaveService;
import com.dgut.staffmodule.service.IStaffService;

@Controller
@RequestMapping("/leave")
public class LeaveController {
	@Autowired
	private ILeaveService leaveService;
	@Autowired
	private IStaffService staffService;

	// 流程服务
	@Autowired
	private TaskService taskService;
	@Autowired
	private RuntimeService runtimeService;

	/**
	 * 保存请假单
	 *
	 * @param leave
	 *            前端返回的假单
	 */
	@RequestMapping("/saveOrUpdate")
	public @ResponseBody ExtAjaxResponse saveOrUpdate(Leave leave) {
		try {
			leaveService.save(leave, leave.getStatus());
			return new ExtAjaxResponse(true, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtAjaxResponse(false, "操作失败!");
		}
	}

	/**
	 * 删除请假单
	 *
	 * @param id
	 *            前端返回的假单id
	 */
	@RequestMapping("/delete")
	public @ResponseBody ExtAjaxResponse delete(@RequestParam("id") Long id) {
		try {
			leaveService.delete(id);
			return new ExtAjaxResponse(true, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtAjaxResponse(false, "操作失败!");
		}
	}

	/**
	 * 查找个人的请假单
	 *
	 * @param leaveQueryDTO
	 *            封装假单的数据传输对象
	 * 
	 * @param session
	 *            获取当前登录的用户
	 * 
	 * @return
	 */

	@RequestMapping(value = "/leaveList")
	public @ResponseBody Page<Leave> findLeaveByUserId(LeaveQueryDTO leaveQueryDTO, HttpSession session,
			ExtPageable pageable) {
		Page<Leave> page = new PageImpl<Leave>(new ArrayList<Leave>(), pageable.getPageable(), 0);
		try {
			String userId = SessionUtil.getUserName(session);
			leaveQueryDTO.setUserId(userId);
			page = leaveService.findPage(LeaveQueryDTO.getSpecification(leaveQueryDTO), pageable.getPageable());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return page;
	}
	/*-------------------------------------流程引擎web层------------------------------------------*/

	/**
	 * 启动流程
	 * 
	 * @param leaveId
	 *            请假信息Id
	 * @param session
	 *            通过会话获取登录用户(请假人)
	 * @return
	 */
	@RequestMapping(value = "/start")
	public @ResponseBody ExtAjaxResponse start(@RequestParam("id") Long leaveId, HttpSession session) {
		try {
			Map<String, Object> variables = new HashMap<String, Object>();
			Leave leave = leaveService.findOne(leaveId);
			String status = "审核中";
			leaveService.save(leave, status);

			// 查找提交申请的上司staff表的对象对应在USER表的ID
			/*
			 * List<String> id= staffService.findDepartmentLeader(leave.getUserId());
			 * System.out.println(id); Staff staff =
			 * staffService.findByStaffName(leave.getUserId()); Staff deptLeader =
			 * staffService.findDepartmentLeader(staff.getDepartment().getId());
			 * 
			 * //查找User表的对应的用户ID User user =
			 * userService.findByName(deptLeader.getStaffName());
			 * 
			 * variables.put("deptLeader", deptLeader.getStaffName());
			 * variables.put("deptId", id);
			 */
			variables.put("applyUserId", SessionUtil.getUserName(session));

			leaveService.startWorkflow(leaveId, variables);

			return new ExtAjaxResponse(true, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtAjaxResponse(false, "操作失败!");
		}
	}

	/**
	 * 查询待处理流程任务
	 * 
	 * @param pageable
	 *            分页对象
	 * @param session
	 *            通过会话获取登录用户(请假人)
	 * @return
	 */
	@RequestMapping(value = "/findTasks")
	public @ResponseBody Page<LeaveQueryDTO> findTodoTasks(HttpSession session, ExtPageable pageable) {
		Page<LeaveQueryDTO> page = new PageImpl<LeaveQueryDTO>(new ArrayList<LeaveQueryDTO>(), pageable.getPageable(),
				0);
		try {
			page = leaveService.findTodoTasks(SessionUtil.getUserName(session), pageable.getPageable());// SessionUtil.getUser(session).getId()
		} catch (Exception e) {
			e.printStackTrace();
		}
		return page;
	}

	/**
	 * 签收任务
	 */
	@RequestMapping(value = "claim/{id}")
	public @ResponseBody ExtAjaxResponse claim(@PathVariable("id") String taskId, HttpSession session) {
		try {
			leaveService.claim(taskId, SessionUtil.getUserName(session));
			return new ExtAjaxResponse(true, "任务签收成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtAjaxResponse(false, "任务签收失败!");
		}
	}

	/**
	 * 完成任务
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "complete/{id}")
	public @ResponseBody ExtAjaxResponse complete(@PathVariable("id") String taskId, WorkflowVariable var,
			HttpSession session) {
		try {
			Map<String, Object> variables = var.getVariableMap();
			// 获取完成任务的business key将请假单的状态更改未审核通过或不通过
			Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
			// 2 通过任务对象获取流程实例
			ProcessInstance pi = runtimeService.createProcessInstanceQuery()
					.processInstanceId(task.getProcessInstanceId()).singleResult();
			// 3 通过流程实例获取“业务键”
			String businessKey = pi.getBusinessKey();
			Long leaveId = Long.parseLong(businessKey);// String 转换为Long
			Leave leave = leaveService.findOne(leaveId);
			String status;
			if (variables.get("deptLeaderPass").equals(false)) {
				status = "审核不通过";
				leaveService.save(leave, status);
			}
			String HRName = staffService.findHRLeader();
			if (SessionUtil.getUserName(session).equals(HRName) && variables.get("deptLeaderPass").equals(true)) {
				status = "审核通过";
				leaveService.save(leave, status);
			}
			System.out.println(businessKey);
			leaveService.complete(taskId, variables);
			return new ExtAjaxResponse(true, "任务完成!");
		} catch (Exception e) {
			e.printStackTrace();
			return new ExtAjaxResponse(false, "任务失败!");
		}
	}
}
